package com.example.todolist;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;

public class NewItemFragment extends BaseFragment {
	
	private EditText myEditText;
	
	private OnNewItemAddedListener onNewItemAddedListener;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		view = inflater.inflate(R.layout.new_item_fragment, container, false);
		
		findViews();
		bindEvents();
		
		return view;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		try {
			onNewItemAddedListener = (OnNewItemAddedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnNewItemAddedListener");
		}
	}

	@Override
	public void initValues() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void findViews() {
		if(view != null) {
			myEditText = (EditText) view.findViewById(R.id.myEditText);
		}
	}

	@Override
	public void bindEvents() {
		if(myEditText != null) {
			myEditText.setOnKeyListener(new OnKeyListener() {
				
				@Override
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					if(event.getAction() == KeyEvent.ACTION_DOWN) {
						if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || (keyCode == KeyEvent.KEYCODE_ENTER)) {
							String newItem = myEditText.getText().toString().trim();
							onNewItemAddedListener.onNewItemAdded(newItem);
							myEditText.setText("");
							return true;
						}
					}
					return false;
				}
			});
		}
	}
	
	public interface OnNewItemAddedListener {
		public void onNewItemAdded(String newItem);
	}
	
}
